<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.marketingTaskName"
        placeholder="输入营销名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
        size="small "
        clearable
      />

      <el-select
        v-model="listQuery.state"
        placeholder="所有状态"
        clearable
        style="width: 150px"
        class="filter-item"
        size="small"
      >
        <el-option
          v-for="item in stateOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="listQuery.sendingType"
        placeholder="所有方式"
        clearable
        style="width: 150px"
        class="filter-item"
        size="small"
        v-show="this.pageName==='EmailSendHistory'"
      >
        <el-option
          v-for="item in sendTypeOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="listQuery.details"
        placeholder="详细"
        multiple
        collapse-tags
        clearable
        style="width: 180px"
        class="filter-item"
        size="small"
        @change="handleDetailsOptionsChange"
        @remove-tag="handleRemoveDetailsOptionsTag"
        @clear="handleClearDetailsOptionsTag"
      >
        <el-option
          v-for="item in detailsOptionsTemp"
          :key="item.key"
          :label="item.label"
          :value="item.key"
          :disabled="item.disabled"
        />
      </el-select>
      <date-selector v-model="listQuery.createdAt" type="daterange" style="width: 300px; vertical-align: middle" value-format="yyyy-MM-dd" />
      <div style="display:inline-block;margin-right:10px;"></div>
      <el-button
        plain
        v-waves
        class="filter-item"
        type="primary"
        size="small"
        icon="el-icon-search"
        @click="handleFilter()"
      >
        {{ $t('table.search') }}
      </el-button>
      <el-button
        plain
        size="mini"
        class="filter-item"
        style="margin-left: 10px"
        type="warning"
        icon="el-icon-s-promotion"
        @click="createMarketingTaskByServer"
        v-show="isServerSend"
      >
        服务器发送
      </el-button>
      <el-button
        plain
        class="filter-item"
        style="margin-left: 10px"
        type="success"
        size="mini"
        icon="el-icon-s-promotion"
        @click="handleEmailSendFree"
        v-show="this.pageName==='EmailSendFree'"
      >
        免费发送
      </el-button>
      <el-button
        size="small"
        class="filter-item right filter-left filter-refresh"
        icon="el-icon-refresh"
        type="primary"
        plain
        @click="refresh()"
      >
      刷新
      </el-button>
      <!-- <el-button
        plain
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        size="small"
        @click=""
      >
        批量删除
      </el-button> -->
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :height="listQuery.total>0 ? 'calc(100vh - 205px)' : 'calc(100vh - 170px)'"
    >
       <el-table-column
        align="center"
        width="50"
        type="index"
        label="序号"
      >
      </el-table-column>
      <el-table-column
        label="客户信息"
        align="center"
        min-width="60px"
      >
        <template slot-scope="{row}">
          <span v-if="row.name">{{ row.name }}</span>
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column
        label="客户邮箱"
        align="center"
        min-width="90px"
      >
        <template slot-scope="{row}">
          {{ row.receiverEmail }}
        </template>
      </el-table-column>
      <el-table-column
        label="发送类型"
        align="center"
        min-width="40px"
        v-if="this.pageName==='EmailSendHistory'"
      >
        <template slot-scope="{row}">
          <template v-for="item in sendTypeOptions">
            <template v-if="item['key'] == row.sendingType">
              <span :key="item['key']" :class="item.class">{{ item.label }}</span>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        label="发送邮箱"
        align="center"
        min-width="90px"
      >
        <template slot-scope="{row}">
          {{ row.senderEmail }}
        </template>
      </el-table-column>
      <el-table-column
        label="发送时间"
        min-width="70px"
        align="center"
      >
        <template slot-scope="{row}">
          <span>{{ row.createdAt }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        min-width="50px"
        align="center"
      >
        <template slot-scope="{row}">
          <template v-for="item in stateOptions">
            <template v-if="item['key'] === row.state">
              <span :class="item.class" v-bind:key="item['key']">{{ item.label }}</span>
            </template>
          </template>
        </template>
      </el-table-column>

      <el-table-column
        label="营销任务来源"
        align="center"
        min-width="100px"
      >
        <template slot-scope="{row}">
          <span class="link-type" @click="handleShowSendDataTracking(row.source)">
            <el-tag type="info">{{ row.marketingTaskName }}</el-tag>
          </span>
        </template>
      </el-table-column>
       <el-table-column
        label="详细"
        align="center"
        min-width="90px"
      >
        <template slot-scope="{row}">
          <el-button-group>
            <!-- v-show会导致显示的按钮缺少圆角样式 -->
            <!-- 可以打包到对象数组中循环实现 -->
            <!-- <el-button type="success" size="mini" v-if="row.isOpen" @click="handleDetailsMessage('read',row.messageIDString)">已打开</el-button>
            <el-button type="success" size="mini" v-if="row.isSent" @click="handleDetailsMessage('reply',row.messageIDString)">已回复</el-button>
            <el-button type="success" size="mini" v-if="row.isBounce" @click="handleDetailsMessage('subscribe',row.messageIDString)">被订阅</el-button>
            <el-button type="warning" size="mini" v-if="row.isUnsub" @click="handleDetailsMessage('unsubscribe',row.messageIDString)">被取消订阅</el-button>
            <el-button type="primary" size="mini" v-if="row.isClick" @click="handleDetailsMessage('clickLink',row.messageIDString)">点击链接</el-button>
            <el-button type="danger" size="mini" v-if="row.isSpam" @click="handleDetailsMessage('spam',row.messageIDString)">被标记垃圾邮件</el-button>
            <el-button type="danger" size="mini" v-if="row.isBlocked" @click="handleDetailsMessage('block',row.messageIDString)">被拉黑</el-button> -->
          <template v-for="item in detailsOptionsTemp">
            <el-button
              :type="item.buttonGroupType"
              :key="item.key"
              size="mini"
              v-if="item.buttonGroup && row[item.buttonGroupShow]"
              @click="handleDetailsMessage(item.eventName,row.messageIDString)">
              {{ item.label }}
            </el-button>
          </template>
          </el-button-group>
        </template>
      </el-table-column>
<!--
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        min-width="120"
        class-name="fixed-width"
      >
        <template slot-scope="{row, $index}">
          <el-button
            style="color:#FF7908;border-color:#FF7908;"
            size="mini"
            @click="handleCopy(row)"
          >
            克隆
          </el-button>
          <el-button
            style="color:#FF7908;border-color:#FF7908;"
            size="mini"
            @click="handleDelete(row)"
          >
            标记客户
          </el-button>
          <el-button
            style="color:#FF7908;border-color:#FF7908;"
            size="mini"
            @click="handleDelete(row)"
          >
            添加客户到联系人
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <showSendDataTracking :show.sync="showSendDataTrackingVisible" :rowId="sendDataTrackingId" />
    <pagination
      v-show="listQuery.total>0"
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList()"
    />
    <el-dialog
      title="详情"
      :visible.sync="centerDialogVisible"
      width="35%"
      top="100px"
      height="700px"
      center
      @close="handleDetailsDialogClose"
      >
      <div v-if="this.detailsList.length > 0">
        <el-scrollbar :wrap-class="{wrapClass: true}" class="dialog-scrollbar">
          <el-collapse v-model="activeDeatilsNames" @change="handleDetailsTypeChange">
            <template v-for="(item,index) in detailsList">
              <el-collapse-item :key="index" title="一致性 Consistency" :name="index" >
                <template slot="title">
                  <el-tag type="info" plain style="font-size:16px;">时间 ：{{ item.createdAt }};    事件 ：{{ getEventName(item.event) }}</el-tag>
                </template>
                <el-card>
                  <el-form label-width="100px">
                    <el-form-item label="客户邮箱:">
                      <el-tag type="primary" plain style="font-size:16px;">{{ item.email }}</el-tag>
                    </el-form-item>
                    <el-form-item label="事件:">
                      <el-tag type="success" plain style="font-size:16px;">{{ getEventName(item.event) }}</el-tag>
                    </el-form-item>
                    <el-form-item label="打开时间:">
                      <el-tag type="primary" plain style="font-size:16px;">{{ timestampToTime(item.time) }}</el-tag>
                    </el-form-item>
                    <el-form-item label="国家:">
                      <el-tag type="primary" plain style="font-size:16px;">{{ getCountry(item.data) }}</el-tag>
                    </el-form-item>
                    <el-form-item label="IP:">
                      <el-tag type="primary" plain style="font-size:16px;">{{ getIp(item.data) }}</el-tag>
                    </el-form-item>
                    <el-form-item label="设备/媒介:">
                      <el-tag type="primary" plain style="font-size:16px;">{{ getAgent(item.data) }}</el-tag>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-collapse-item>
            </template>
          </el-collapse>
        </el-scrollbar>
      </div>
      <div v-else>
        <div style="text-align:center;padding-top:10px;">
          暂无数据
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleDetailsDialogClose">取 消</el-button>
        <el-button type="primary" @click="handleDetailsDialogClose">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index.vue'
import { getAction, postAction } from '@/api/common'
import DateSelector from '@/components/Public/dateSelector.vue'
import showSendDataTracking from '../emailMarketingTask/showSendDataTracking.vue'

export default {
  name: 'EmailSendHistoryIndex',
  components: {
    DateSelector,
    Pagination,
    showSendDataTracking
  },
  data() {
    const detailsOptions = [
      { key: 2, label: '已发送', icon: 'el-icon-circle-check', class: 'notSet', disabled: false, eventName: 'sent', buttonGroup: true, buttonGroupType: 'warning', buttonGroupShow: 'isSent' },
      { key: 1, label: '已打开', icon: 'el-icon-edit-outline', class: 'notSet', disabled: false, eventName: 'open', buttonGroup: true, buttonGroupType: 'success', buttonGroupShow: 'isOpen' },
      { key: -1, label: '未打开', icon: 'el-icon-edit-outline', class: 'notSet', disabled: false, eventName: 'notOpen', buttonGroup: false, buttonGroupType: 'success', buttonGroupShow: 'isOpen' }, // 特殊
      { key: 4, label: '被退回', icon: 'el-icon-circle-check', class: 'notSet', disabled: false, eventName: 'bounce', buttonGroup: true, buttonGroupType: 'warning', buttonGroupShow: 'isBounce' },
      { key: 8, label: '被取消订阅', icon: 'el-icon-circle-check', class: 'notSet', disabled: false, eventName: 'unsub', buttonGroup: true, buttonGroupType: 'success', buttonGroupShow: 'isUnsub' },
      { key: 16, label: '点击链接', icon: 'el-icon-circle-check', class: 'notSet', disabled: false, eventName: 'click', buttonGroup: true, buttonGroupType: 'primary', buttonGroupShow: 'isClick' },
      { key: 32, label: '被标记垃圾邮件', icon: 'el-icon-circle-check', class: 'notSet', disabled: false, eventName: 'spam', buttonGroup: true, buttonGroupType: 'danger', buttonGroupShow: 'isSpam' },
      { key: 64, label: '邮箱被拉黑', icon: 'el-icon-circle-check', class: 'notSet', disabled: false, eventName: 'blocked ', buttonGroup: true, buttonGroupType: 'danger', buttonGroupShow: 'isBlocked' }
    ]
    return {
      list: [],
      listLoading: false,
      centerDialogVisible: false,
      detailsList: [],
      activeDeatilsNames: [0],
      listQuery: {
        page: 1,
        limit: 20,
        total: 0,
        marketingTaskName: undefined,
        type: undefined,
        sendingType: undefined,
        createdAt: undefined,
        details: undefined,
        pageName: ''
      },
      detailsOptionOldValue: [],
      showSendDataTrackingVisible: false,
      sendDataTrackingId: 0,
      stateOptions: [
        { key: true, label: '成功', icon: 'el-icon-edit-outline', class: 'state_unsubmit' },
        { key: false, label: '失败', icon: 'el-icon-circle-check', class: 'state_submit' }
      ],
      sendTypeOptions: [
        { key: '1', label: '免费发送', icon: 'el-icon-edit-outline', class: 'state_unsubmit' },
        { key: '2', label: '服务器发送', icon: 'el-icon-circle-check', class: 'state_submit' }
      ],
      detailsOptions,
      detailsOptionsTemp: JSON.parse(JSON.stringify(detailsOptions))
    }
  },
  created() {
    this.getList()
  },
  computed: {
    pageName() {
      const path = this.$route.path
      if (path.includes('emailSendHistory')) {
        return 'EmailSendHistory'
      } else if (path.includes('emailSendFree')) {
        return 'EmailSendFree'
      } else if (path.includes('emailServerSend')) {
        return 'EmailServerSend'
      } else if (path.includes('emailRushEmailSend')) {
        return 'EmailRushEmailSend'
      }
      return undefined
    },
    isServerSend() {
      return this.pageName === 'EmailServerSend' || this.pageName === 'EmailRushEmailSend'
    }
  },
  methods: {
    refresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        total: 0,
        marketingTaskName: undefined,
        type: undefined,
        sendingType: undefined,
        createdAt: undefined,
        details: undefined,
        pageName: this.pageName
      }
      this.getList()
    },
    getEventName(val) {
      for (const item in this.detailsOptions) {
        console.log(item)
        if (this.detailsOptions[item].eventName === val) {
          return this.detailsOptions[item].label
        }
      }
    },
    getList() {
      this.listLoading = true
      this.listQuery.pageName = this.pageName
      postAction(this.listQuery, 'EmailSendHistory/index')
        .then(({ data }) => {
          this.list = data.items
          this.listQuery.total = data.total
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDetailsOptionsChange(val) {
      console.log(val)
      this.getDetailsOptionsDisabledValue(val)
    },
    getDetailsOptionsDisabledValue(val) {
      this.detailsOptionsTemp = this.detailsOptionsTemp.map((m) =>
        ({ ...m, disabled: val.indexOf(-m.key) !== -1 }))
    },
    handleRemoveDetailsOptionsTag(val) {
    // 上方input框每个选项的小叉叉触发
      this.detailsOptionsTemp = this.detailsOptionsTemp.map((m) => {
        if (m.key === -val) {
          m.disabled = false
        }
        return m
      })
    },
    handleClearDetailsOptionsTag() {
    // 上方input框后的小叉叉触发
    // 重置值
      console.log('clear')
      this.detailsOptionsTemp = JSON.parse(JSON.stringify(this.detailsOptions))
    },
    handleShowSendDataTracking(value) {
      this.showSendDataTrackingVisible = true
      console.log('value', value)
      this.sendDataTrackingId = value
    },
    handleEmailSendFree() {
      this.$router.push('/email/emailSendFree/add?fromPage=Index')
    },
    createMarketingTaskByServer() {
      let uri = '/email/emailServerSend/add?fromPage=Index'
      if (this.pageName === 'EmailRushEmailSend') {
        uri += '&server=rushemail'
      }
      this.$router.push(uri)
    },
    handleDetailsMessage(eventType, messageId) {
      this.centerDialogVisible = true
      console.log(eventType)
      getAction({ messageId, eventType }, 'EmailSendHistory/GetDetailsByMessageId')
        .then(res => {
          this.detailsList = res.data
          console.log(res)
        }).finally(() => {
          console.log('获取邮件详情结束')
        })
    },
    handleDetailsTypeChange(val) {
      console.log(val)
    },
    handleDetailsDialogClose() {
      this.centerDialogVisible = false
      this.detailsList = []
    },
    getCountry(val) {
      const jsonData = JSON.parse(val)
      return jsonData.geo ?? '暂无'
    },
    getIp(val) {
      const jsonData = JSON.parse(val)
      return jsonData.ip ?? '暂无'
    },
    getAgent(val) {
      const jsonData = JSON.parse(val)
      return jsonData.agent ?? '暂无'
    },
    timestampToTime(timestamp) {
      const date = new Date(timestamp * 1000)
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
      const s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
      return Y + M + D + h + m + s
    },
    getShowResult(row, name) {
      return row[name] === true
    }
  }

}

</script>

<style scoped>

  .state_unsubmit{
    color:#609CD3;
  }

  .state_unsubmit > i{
    font-size: 20px;
    margin-right: 5px;
  }

  .state_submit{
    color:plum;
  }

  .state_submit > i{
    font-size: 20px;
    margin-right: 5px;
  }

  .state_cancel{
    color:orange;
  }

  .state_cancel > i{
    font-size: 20px;
    margin-right: 5px;
  }

  .state_complete{
    color:green;
  }

  .state_complete > i{
    font-size: 20px;
    margin-right: 5px;
  }

  .count_icon > i{
    color:#FF7908;
    font-size: 20px;
    margin-right: 5px;
  }

  .dialog-scrollbar {
      height: 620px;
    }

</style>
